<template>
  <section class="search-group" style="padding: 12px;" v-if="searchItem.length > 0">
    <el-form :inline="true" :model="searchFormInline" ref="searchFormInline" class="form_search" size="default">
      <el-row>
        <el-col
          v-for="(item, index) in searchItem"
          :key="index"
          :span="item.span || 6"
          v-show="showMore || searchItemShowFlag(index)"
          :style="{
            textAlign: item.align ? item.align : 'left',
            marginLeft: item.marginLeft || '0px',
            width: item.colWidth,
          }"
        >
          <el-form-item
            :label="item.label || ''"
            :prop="item.name"
            :label-width="item.label && item.label.length > 7 ? 150+'px' : 100+'px'"
            v-if="item.type !== 'mulSelete'"
          >
            <el-input
              v-model="searchFormInline[item.name]"
              :placeholder="item.placeholder || item.label"
              :size="item.size || 'default' "
              clearable
              :maxlength="item.maxlength || 50"
              v-if="item.type === 'text'"
              style="width: 100%"
            ></el-input>

            <el-select
              filterable
              clearable
              :size="item.size || 'default' "
              style="width: 100%"
              v-if="item.type === 'selectFilter'"
              v-model="searchFormInline[item.name]"
              placeholder="请选择"
            >
              <el-option v-for="option in item.options" :key="option.value" :value="option.value" :label="option.label" />
            </el-select>
            <el-select
              :style="{width: item.fieldWidth ? `${item.fieldWidth}px` : '100%'}"
              v-model="searchFormInline[item.name]"
              placeholder="请选择"
              :size="item.size || 'default' "
              :clearable="!(item.name == 'timeSelect')"
              v-if="item.type === 'select'"
              @change="(val) => changeModelVal(val, item)"
            >
              <el-option
                v-for="citem in item.options"
                :key="citem['value'] || citem.code"
                :label="citem[item.labelFiled||'label'] || citem.name"
                :value="citem[item.valueFiled||'value'] || citem.code"
              >
              </el-option>
            </el-select>

            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="date"
              :size="item.size || 'default' "
              clearable
              v-if="item.type === 'date'"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="date"
              :size="item.size || 'default' "
              clearable
              v-if="item.type === 'datetime'"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="month"
              :size="item.size || 'default' "
              clearable
              v-if="item.type === 'datemonth'"
              value-format="YYYY-MM"
              placeholder="选择月">
            </el-date-picker>
            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="year"
              :size="item.size || 'default' "
              :clearable="item.clearable"
              v-if="item.type === 'dateyear'"
              value-format="YYYY"
              placeholder="选择年">
            </el-date-picker>

            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="datetimerange"
              :size="item.size || 'default' "
              clearable
              v-if="item.type === 'datetimerange'"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
            <el-date-picker
              v-model="searchFormInline[item.name]"
              type="daterange"
              :size="item.size || 'default' "
              clearable
              v-if="item.type === 'daterange'"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            :label="item.label"
            :prop="item.name"
            v-if="item.type == 'mulSelete'"
            class="mul_select"
          >
            <el-select
              v-model="searchFormInline['mulSelectAarray']"
              placeholder="请选择"
              :size="item.size || 'default' "
              multiple
              clearable
              filterable
              style="width: 910px"
              @change="changeSelect"
            >
              <el-option
                v-for="citem in item.options"
                :key="citem['value']"
                :label="citem[item.labelFiled||'label']"
                :value="citem[item.valueFiled||'value']"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="inline_btn" v-if="showType == 'inline'">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset('searchFormInline')">重置</el-button>
        </el-col>
      </el-row>
        <div class="search_btn" v-if="showType != 'inline'">
          <el-button type="primary" link @click="handleToggleMore" v-if="searchItemTotalLength > (24 * defaultShowLineNum)" >
            {{!showMore ? '展开' : '收起'}}更多搜索
          </el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset('searchFormInline')">重置</el-button>
        </div>
    </el-form>
  </section>
</template>

<script>

export default {
  name: 'SearchGroup',
  props: {
    resetType: {
      type: Boolean,
      default: function () {
        return false;
      }
    },
    searchItem: {
      type: Array,
      default: function () {
        return [];
      }
    },
    showType: {
      type: String,
      default: function () {
        return '';
      }
    },
    selectClearable: {
      type: Boolean,
      default: function () {
        return true;
      }
    },
    defaultShowLineNum: {
      type: Number,
      default: 2
    }
  },
  data() {
    const date = new Date();
    return {
      searchFormInline: {
        mulSelectAarray: [],
      },
      isChange: false, // 只监听首次进来取值，后续值更具changeModalVal的变值更改
      oldMulSelectAarray: [],
      showMore: false
    };
  },
  mounted() {

  },
  computed: {
    route: function () {
      return this.$route.path;
    },
    defaultShowTwoLineLength() {
      let totalSpan = 0;
      for (let index = 0; index < this.searchItem.length; index++) {
        const element = this.searchItem[index];
        if (totalSpan + (element.span || 6) > (this.defaultShowLineNum * 24)) {
          break;
        }
        totalSpan += (element.span || 6)
      }
      return totalSpan;
    },
    searchItemTotalLength() {
      return this.searchItem.reduce((pre, cur) => pre + (cur.span || 6), 0)
    }
  },
  watch: {
    resetType: function (nVal, oVal) {
      if (nVal) {
        this.handleReset();
      }
    },
    searchItem: {
      handler(val) {
        val.forEach(item => {
          if(item.defaultVal && !this.isChange) {
            this.searchFormInline[item.name] = item.defaultVal == 'emptyString' ? '' :  item.defaultVal;
          }
        })
      },
      immediate: true,
      deep: true
    },
  },
  methods: {
    // 判断搜索条件展示与否
    searchItemShowFlag(index) {
      let arr = [...this.searchItem.slice(0, index + 1)]
      let res = arr.reduce((pre, cur) => pre += (cur.span || 6), 0)
      // console.log('searchItemShowFlag',res, span);
      return res <= this.defaultShowTwoLineLength
    },
    
    handleSearch() {
      let searchParams = { ...this.searchFormInline };
      let selParam = this.searchItem.find(item => item.type == 'mulSelete');
      if (selParam) {
        if (!(searchParams.mulSelectAarray instanceof Array && searchParams.mulSelectAarray.length > 0)) {
          searchParams[selParam.name] = undefined;
        } else {
          searchParams[selParam.name] = searchParams.mulSelectAarray;
        }
      } else {
        delete searchParams.mulSelectAarray;
      }
      // this.searchFormInline.mulSelectAarray = undefined

      this.$emit('handleSearch', searchParams);
    },
    handleReset(formName) {
      this.searchItem.forEach((item, index) => {
        if (item.type == 'mulSelete') {
          this.searchFormInline.mulSelectAarray = [];
        } else if (item.defaultVal == 'emptyString') {
          this.searchFormInline[item.name] = '';
        } else if (item.type == 'dateyear') {
          this.searchFormInline[item.name] = String(new Date().getFullYear());
        } else {
          if (this.searchFormInline[item.name]) {
            this.searchFormInline[item.name] = item.defaultVal || '';
            this.$forceUpdate();
          }
        }
      });
    },
    handleToggleMore() {
      this.showMore = !this.showMore;
    },
    changeModelVal(val, item) {
      this.searchFormInline[item.name] = val;
      this.isChange = true;
      this.$forceUpdate();
    },
    changeSelect(val) {
      const allValues = [];
      let obj = {};
      obj = this.searchItem.find((item) => {
        return item.label === '关区';
      });
      if (!obj) {
        return;
      }
      // 保留所有值
      for (const item of obj.options) {
        allValues.push(item.value);
      }
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldMulSelectAarray.length === 1 ? this.oldMulSelectAarray[0] : [];
      // 若是全部选择
      if (val.includes('ALL_SELECT')) this.searchFormInline.mulSelectAarray = allValues;
      // 取消全部选中 上次有 当前没有 表示取消全选
      if (oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) this.searchFormInline.mulSelectAarray = [];
      // 点击非全部选中 需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes('ALL_SELECT') && val.includes('ALL_SELECT')) {
        const index = val.indexOf('ALL_SELECT');
        val.splice(index, 1); // 排除全选选项
        this.searchFormInline.mulSelectAarray = val;
      }
      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes('ALL_SELECT') && !val.includes('ALL_SELECT')) {
        if (val.length === allValues.length - 1) this.searchFormInline.mulSelectAarray = ['ALL_SELECT'].concat(val);
      }
      // 储存当前最后的结果 作为下次的老数据
      this.oldMulSelectAarray[0] = this.searchFormInline.mulSelectAarray;
    },
  }
};
</script>

<style lang="scss" rel="style/scss" scoped>
 .search-group {
  border: 1px solid #e6ebf5;
  background: #fff;
  padding-top: 10px;
  // margin: 0 10px;
  .form_search {
    padding: 0 0;
    text-align: center;
  }
  .search_btn {
    margin: 10px 0 10px;
  }
  .el-row {
    transition: all 0.3s;
  }
  .inline_btn {
    padding: 5px 15px;
    text-align: left;
  }
  .mul_select {
    width: 100%;
    text-align: left;
  }
  .el-form-item__content {
    width: 800px;
  }
}
.el-form--inline .el-form-item {
  display: flex;
  margin-right: 0;
}
</style>
